package com.bobo.db;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created by anting on 16/10/14.
 */
public class DataSourceUtils {

    private static DataSource ds;
    //声明ThreadLocal容器对象
    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    static {
        try {
            InputStream in = DataSourceUtils.class.getClassLoader()
                    .getResourceAsStream("ds.properties");
            Properties props = new Properties();
            props.load(in);
            ds = DruidDataSourceFactory.createDataSource(props);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static Connection getConn() throws SQLException {

        Connection con = null;
        //先从tl中获取数据
        con = tl.get();
        if (con == null) {
            try {
                con = ds.getConnection();
                //将新取得的连接放到该线程中
                tl.set(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return con;

    }

    public static void remove() {
        //清理该线程中的连接
        tl.remove();

    }

}
